<?php

// WEB 入口页面

if (preg_match('#\.(css|js|map|ico|gif|jpg|jpeg|png|bmp|eot|otf|ttf|woff|woff2|svg|htaccess|ini|git|gitignore|env|example|sql|md|key)#i', $_SERVER["REQUEST_URI"])) {
	return false;
}

version_compare(PHP_VERSION, '7.1.3', '>=') || die('Requires PHP 7.1.3+');
date_default_timezone_set('PRC');
define('IN_SFRAME', true);
define('ROOT_PATH', realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR);
define('APP_PATH', ROOT_PATH . 'app' . DIRECTORY_SEPARATOR);
define('CONFIG_PATH', ROOT_PATH . 'config' . DIRECTORY_SEPARATOR);

require ROOT_PATH . "vendor/autoload.php";

use Symfony\Component\Routing;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\EventDispatcher\EventDispatcher;

use sframe\Config;
use sframe\Subscriber;
use sframe\ExceptionHandler;
use sframe\ControllerResolver;

define('APP_DEBUG', Config::get("app_debug"));

if (APP_DEBUG) {
	Debug::enable(E_ALL, APP_DEBUG);
}

try {
	$routes = include ROOT_PATH . 'routes/routes.php';
	$context = new Routing\RequestContext();
	$matcher = new Routing\Matcher\UrlMatcher($routes, $context);

	$request = Request::createFromGlobals();
	$request->attributes->add($matcher->match($request->getPathInfo()));

	$dispatcher = new EventDispatcher();
	$dispatcher->addSubscriber(new Subscriber(APP_DEBUG));

	$httpKernel = new HttpKernel\HttpKernel($dispatcher, new ControllerResolver(), new RequestStack());

	$response = $httpKernel->handle($request, HttpKernel\HttpKernelInterface::MASTER_REQUEST);
	$response->send();
	$httpKernel->terminate($request, $response);
}
catch (Throwable $exception) {
	ExceptionHandler::process($exception, APP_DEBUG)->send();
}
